package com.fiona.remoting.api;

import java.net.InetAddress;
import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.net.NetUtil;

public abstract class AbstractServer implements Server {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private InetSocketAddress bindAddress;
	private int bindPort;

	protected abstract void doOpen() throws Throwable;

	protected abstract void doClose() throws Throwable;

	public InetSocketAddress getBindAddress() {
		return bindAddress;
	}

	public AbstractServer(InetSocketAddress address) {
		bindPort = address.getPort();
		this.start();
	}

	@Override
	public void start() {
		InetAddress bindIp = NetUtil.getLocalhost();
		bindAddress = new InetSocketAddress(bindIp, bindPort);
		try {
			new Thread(() -> {
				try {
					doOpen();
				} catch (Throwable e) {
					throw ExceptionUtil.wrapRuntime(e);
				}
			}, Constants.SERVER_THREAD_POOL_NAME.concat("-" + Constants.ATOMIC_INTEGER.getAndIncrement())).start();
			if (logger.isInfoEnabled()) {
				logger.info("Start " + getClass().getSimpleName() + " bind " + getBindAddress());
			}
		} catch (Throwable t) {
			throw ExceptionUtil.wrapRuntime(t);
		}

	}

}
